<template>
	<view class="index-page">
		<!-- 状态栏占位 -->
		<view class="status-bar"></view>
		
		<!-- 顶部导航区域 -->
		<view class="header-section">
			<view class="header-content">
				<view class="welcome-info">
					<text class="welcome-text">欢迎，</text>
					<text class="username">{{userInfo.user && userInfo.user.nickname || '游客'}}</text>
				</view>
				<view class="location-info" @click="refreshLocation">
					<text class="location-icon">📍</text>
					<text class="location-text">{{currentLocation}}</text>
				</view>
			</view>
		</view>
		
		<!-- 地图容器 -->
		<view class="map-container">
			<map
				class="map"
				:latitude="latitude"
				:longitude="longitude"
				:scale="mapScale"
				:markers="markers"
				@markertap="handleMarkerTap"
				@regionchange="handleRegionChange"
				show-location
				enable-3D
				enable-overlooking
				enable-zoom
				enable-scroll
				enable-rotate
			>
			</map>
			
			<!-- 地图控制按钮 -->
			<view class="map-controls">
				<view class="control-btn" @click="zoomIn">
					<image class="control-icon" src="/static/images/zoom-in.png" mode="aspectFit" />
				</view>
				<view class="control-btn" @click="zoomOut">
					<image class="control-icon" src="/static/images/zoom-out.png" mode="aspectFit" />
				</view>
				<view class="control-btn" @click="centerToLocation">
					<image class="control-icon" src="/static/images/location.png" mode="aspectFit" />
				</view>
			</view>
			
			<!-- 地图加载状态 -->
			<view v-if="mapLoading" class="map-loading">
				<view class="loading-spinner"></view>
				<text class="loading-text">加载地图中...</text>
			</view>
		</view>
		
		<!-- 底部信息面板 -->
		<view class="bottom-panel" :class="selectedProject ? 'panel-expanded' : ''">
			<!-- 默认面板：显示统计信息 -->
			<view v-if="!selectedProject" class="default-panel">
				<view class="panel-header">
					<view>
						<text class="panel-title">工程概览</text>
						<text class="project-count">共 {{markers.length}} 个项目</text>
					</view>
					<view class="refresh-btn" @click="refreshData">
						<text class="refresh-icon">🔄</text>
					</view>
				</view>
				
				<!-- 项目统计 -->
				<!-- <view class="project-stats">
					<view class="stat-item">
						<text class="stat-number">{{todayInspections}}</text>
						<text class="stat-label">今日巡查</text>
					</view>
					<view class="stat-divider"></view>
					<view class="stat-item">
						<text class="stat-number">{{pendingIssues}}</text>
						<text class="stat-label">待处理</text>
					</view>
					<view class="stat-divider"></view>
					<view class="stat-item">
						<text class="stat-number">{{completedTasks}}</text>
						<text class="stat-label">已完成</text>
					</view>
				</view> -->
			</view>
			
			<!-- 项目详情面板 -->
			<view v-if="selectedProject" class="project-panel">
				<view class="panel-drag-handle"></view>
				
				<view class="project-header">
					<view class="project-info">
						<text class="project-name">{{selectedProject.csname}}</text>
						<text class="project-address">{{selectedProject.address}}</text>
					</view>
					<view class="project-actions">
						<view class="action-btn primary" @click="viewProjectDetails">
							<text class="btn-text">查看详情</text>
						</view>
						<view class="action-btn secondary" @click="clearSelection">
							<text class="btn-text">关闭</text>
						</view>
					</view>
				</view>
				
				<!-- 项目详细信息 -->
				<view class="project-details">
					<view class="detail-item">
						<text class="detail-label">项目编号</text>
						<text class="detail-value">{{selectedProject.cpid}}</text>
					</view>
					<view class="detail-item">
						<text class="detail-label">项目状态</text>
						<view class="status-badge status-active">
							<text class="status-text">{{selectedProject.pstatus}}</text>
						</view>
					</view>
					<view class="detail-item">
						<text class="detail-label">工程进度</text>
						<view class="status-badge status-qualified">
							<text class="status-text">{{selectedProject.gprogress}}</text>
						</view>
					</view>
					<view class="detail-item">
						<text class="detail-label">负责人</text>
						<text class="detail-value">{{selectedProject.cpman_login_uid}}</text>
					</view>
					<view class="detail-item">
						<text class="detail-label">负责人电话</text>
						<text class="detail-value">{{selectedProject.cpman_mphone}}</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	// 引入新的工具函数和常量
	import { request } from '@/request/index.js'
	import { MAP_CONFIG, STORAGE_KEYS } from '@/constants/index.js'
	import { getStorage, setStorage, showToast, showLoading, hideLoading, validateCoordinates } from '@/utils/index.js'
	
	// 引用高德地图微信小程序JSAPI模块
	const amapFile = null // require('@/comm/amap-wx.js') - 暂时注释以解决模块导入错误

	export default {
		data() {
			return {
				// 地图相关
				markers: [],
				latitude: 30.5734,
				longitude: 114.2734,
				mapScale: 15, // 默认缩放级别
				mapLoading: false,
				currentLocation: '定位中...',
				
				// 用户信息
				userInfo: {},
				
				// 选中的项目
				selectedProject: null,
				
				// 统计数据
				todayInspections: 0,
				pendingIssues: 0,
				completedTasks: 0
			}
		},
		
		onShow() {
			this.checkUserAuth()
			this.loadCachedData()
		},
		
		onLoad() {
			this.initPage()
		},
		
		onPullDownRefresh() {
			this.refreshData()
		},
		
		methods: {
			/**
			 * 初始化页面
			 */
			async initPage() {
				try {
					this.mapLoading = true
					
					// 获取用户信息
					const userInfo = getStorage(STORAGE_KEYS.USER_INFO)
					if (userInfo) {
						this.userInfo = userInfo
					}
					
					// 获取位置
					await this.getCurrentLocation()
					
					// 初始化地图
					this.initMap()
					
					// 加载项目数据
					await this.loadProjectData()
					
					// 加载统计数据
					await this.loadStatistics()
					
				} catch (error) {
					console.error('初始化页面失败:', error)
					showToast('初始化失败，请重试')
				} finally {
					this.mapLoading = false
				}
			},
			
			/**
			 * 检查用户权限
			 */
			checkUserAuth() {
				const userInfo = getStorage(STORAGE_KEYS.USER_INFO)
				if (!userInfo) {
					console.log('用户未登录，使用游客模式')
				}
			},
			
			/**
			 * 加载缓存数据
			 */
			loadCachedData() {
				const location = getStorage(STORAGE_KEYS.LOCATION)
				if (location && location.longitude && location.latitude) {
					 this.longitude = location.longitude
					 this.latitude = location.latitude
					//this.longitude = '80.511028'
					//this.latitude = '30.626594'
				}
			},
			
			/**
			 * 获取当前位置
			 */
			getCurrentLocation() {
				return new Promise((resolve, reject) => {
					uni.getLocation({
						type: 'gcj02',
						success: (res) => {
							 this.latitude = res.latitude
							 this.longitude = res.longitude
							//this.latitude = '80.511028'
							//this.longitude = '30.626594'
							this.currentLocation = '当前位置'
							
							// 缓存位置信息
							setStorage(STORAGE_KEYS.LOCATION, {
								 longitude: res.longitude,
								 latitude: res.latitude,
								//longitude: '80.511028',
								//latitude: '30.626594'
							})
							
							resolve(res)
						},
						fail: (err) => {
							console.error('获取位置失败:', err)
							this.currentLocation = '定位失败'
							uni.showModal({
								title: '位置权限',
								content: '请确认已经打开位置服务，并且授权定位权限',
								showCancel: false
							})
							reject(err)
						}
					})
				})
			},
			
			/**
			 * 初始化地图
			 */
			initMap() {
				try {
					// 暂时注释高德地图初始化，等待模块正确导入
					// const myAmapFun = new amapFile.AMapWX({
					// 	key: MAP_CONFIG.AMAP_KEY
					// })
					console.log('地图初始化暂时跳过')
				} catch (error) {
					console.error('地图初始化失败:', error)
				}
			},
			
			/**
			 * 加载项目数据
			 */
			async loadProjectData() {
				const userInfo = getStorage(STORAGE_KEYS.USER_INFO)
				if (!userInfo) {
					console.log('未登录用户，跳过项目数据加载')
					return
				}
				
				try {
					const response = await request({
						url: '/grid/query/c_cproject-m_cproject',
						method: 'POST',
						header: {
							'Content-Type': 'application/x-www-form-urlencoded',
							'cookie': getStorage(STORAGE_KEYS.TOKEN),
							'map': true
						}
					})
					
					if (response.data.rows) {
						this.processProjectData(response.data.rows)
					}
				} catch (error) {
					console.error('加载项目数据失败:', error)
					showToast('加载数据失败')
				}
			},
			
			/**
			 * 处理项目数据
			 */
			processProjectData(projects) {
				const markers = projects.map((item, index) => {
					// 使用工具函数验证并修正坐标值
					const coords = validateCoordinates(item.latitude, item.longitude);
					
					return {
						id: index,
						cpid: item.cpid,
						width: MAP_CONFIG.MARKER_WIDTH,
						height: MAP_CONFIG.MARKER_HEIGHT,
						latitude: coords.latitude,
						longitude: coords.longitude,
						address: item.paddress,
						csname: item.csname,
						pstatus: item.pstatus,
						gprogress: item.gprogress,
						cpman_login_uid: item.cpman_login_uid,
						cpman_mphone: item.cpman_mphone,
						iconPath: '/static/images/marker.png',
						callout: {
							padding: 2,
							fontSize: 0,
							color: '#ffffff',
							borderRadius: 5,
							display: 'none'
						}
					}
				})
				
				this.markers = markers
				console.log('项目数据加载完成:', markers.length)
				// 输出坐标验证信息
				markers.forEach(marker => {
					console.log(`项目: ${marker.csname}, 坐标: [${marker.longitude}, ${marker.latitude}]`);
				});
			},
			
			/**
			 * 加载统计数据
			 */
			async loadStatistics() {
				// 这里可以添加实际的统计数据接口调用
				// 暂时使用模拟数据
				this.todayInspections = Math.floor(Math.random() * 20) + 5
				this.pendingIssues = Math.floor(Math.random() * 10) + 2
				this.completedTasks = Math.floor(Math.random() * 50) + 10
			},
			
			/**
			 * 处理标记点击击事件
			 */
			handleMarkerTap(e) {
				const markerId = e.detail.markerId
				const marker = this.markers[markerId]
				
				if (marker) {
					// 更新所有标记点的样式
					this.updateMarkerStyles(markerId)
					
					// 设置选中的项目
					this.selectedProject = marker
					
					console.log('选中项目:', marker.csname)
				}
			},
			
			/**
			 * 更新标记点样式
			 */
			updateMarkerStyles(selectedId) {
				const updatedMarkers = this.markers.map((marker, index) => {
					return {
						...marker,
						iconPath: index === selectedId 
							? '/static/images/marker-red.png' 
							: '/static/images/marker.png'
					}
				})
				
				this.markers = updatedMarkers
			},
			
			/**
			 * 地图区域变化事件
			 */
			handleRegionChange(e) {
				if (e.type === 'end') {
					console.log('地图区域变化:', e.detail)
				}
			},
			
			/**
			 * 刷新位置
			 */
			async refreshLocation() {
				showLoading('定位中...')
				try {
					await this.getCurrentLocation()
					showToast('位置更新成功')
				} catch (error) {
					showToast('位置更新失败')
				} finally {
					hideLoading()
				}
			},
			
			/**
			 * 刷新数据
			 */
			async refreshData() {
				try {
					await Promise.all([
						this.loadProjectData(),
						this.loadStatistics()
					])
					showToast('刷新成功')
				} catch (error) {
					showToast('刷新失败')
				} finally {
					uni.stopPullDownRefresh()
				}
			},
			
			/**
			 * 放大地图
			 */
			zoomIn() {
				if (this.mapScale < 18) {
					this.mapScale += 1
				}
			},
			
			/**
			 * 缩小地图
			 */
			zoomOut() {
				if (this.mapScale > 5) {
					this.mapScale -= 1
				}
			},
			
			/**
			 * 定位到当前位置
			 */
			centerToLocation() {
				this.refreshLocation()
			},
			
			/**
			 * 查看项目详情
			 */
			viewProjectDetails() {
				if (this.selectedProject) {
					uni.navigateTo({
						url: `/pages/projectDetails/projectDetails?cproject=${this.selectedProject.cpid}`
					})
				}
			},
			
			/**
			 * 清除选中状态
			 */
			clearSelection() {
				this.selectedProject = null
				// 重置所有标记点样式
				this.markers = this.markers.map(marker => ({
					...marker,
					iconPath: '/static/images/marker.png'
				}))
			}
		}
	}
</script>

<style lang="scss" scoped>
@import '@/styles/variables.scss';

.index-page {
	flex: 1;
	display: flex;
	flex-direction: column;
	height: 100vh;
	background-color: $bg-secondary;
}

/* 状态栏 */
.status-bar {
	height: var(--status-bar-height, 0);
	background: $primary-gradient;
}

/* 顶部导航区域 */
.header-section {
	background: $primary-gradient;
	padding: $spacing-lg $spacing-lg $spacing-xl;
	border-radius: 0 0 $border-radius-xl $border-radius-xl;
	box-shadow: $shadow-base;
}

.header-content {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.welcome-info {
	display: flex;
	align-items: baseline;
	gap: $spacing-xs;
}

.welcome-text {
	font-size: $font-size-base;
	color: rgba(255, 255, 255, 0.8);
}

.username {
	font-size: $font-size-lg;
	font-weight: 600;
	color: $text-white;
}

.location-info {
	display: flex;
	align-items: center;
	gap: $spacing-xs;
	padding: $spacing-xs $spacing-sm;
	background: rgba(255, 255, 255, 0.2);
	border-radius: $border-radius-base;
	transition: $transition-base;

	&:active {
		background: rgba(255, 255, 255, 0.3);
	}
}

.location-icon {
	font-size: $font-size-sm;
}

.location-text {
	font-size: $font-size-sm;
	color: $text-white;
	max-width: 200rpx;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

/* 地图容器 */
.map-container {
	flex: 1;
	position: relative;
	border-radius: $border-radius-lg $border-radius-lg 0 0;
	overflow: hidden;
	margin: $spacing-md;
	margin-bottom: 0;
	box-shadow: $shadow-base;
}

.map {
	width: 100%;
	height: 100%;
}

.map-controls {
	position: absolute;
	top: $spacing-lg;
	right: $spacing-lg;
	display: flex;
	flex-direction: column;
	gap: $spacing-sm;
}

.control-btn {
	width: 80rpx;
	height: 80rpx;
	background: $white;
	border-radius: $border-radius-base;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: $shadow-sm;
	transition: $transition-base;

	&:active {
		transform: scale(0.95);
		box-shadow: $shadow-base;
	}
}

.control-icon {
	width: 32rpx;
	height: 32rpx;
}

.map-loading {
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: $spacing-md;
	padding: $spacing-xl;
	background: rgba(255, 255, 255, 0.9);
	border-radius: $border-radius-lg;
	backdrop-filter: $backdrop-filter;
}

.loading-spinner {
	width: 60rpx;
	height: 60rpx;
	border: 4rpx solid $gray-300;
	border-top-color: $primary-color;
	border-radius: 50%;
	animation: spin 1s linear infinite;
}

@keyframes spin {
	0% { transform: rotate(0deg); }
	100% { transform: rotate(360deg); }
}

.loading-text {
	font-size: $font-size-sm;
	color: $text-secondary;
}

/* 底部信息面板 */
.bottom-panel {
	background: $white;
	border-radius: $border-radius-xl $border-radius-xl 0 0;
	box-shadow: 0 -8rpx 32rpx rgba(0, 0, 0, 0.08);
	transition: $transition-base;
	margin: 0 $spacing-md;
	margin-bottom: $spacing-md;
	min-height: 200rpx;

	&.panel-expanded {
		min-height: 400rpx;
	}
}

/* 默认面板 */
.default-panel {
	padding: $spacing-xl;
}

.panel-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: $spacing-lg;
}

.panel-title {
	font-size: $font-size-lg;
	font-weight: 600;
	color: $text-primary;
}

.project-count {
	font-size: $font-size-sm;
	color: $text-secondary;
	margin-top: $spacing-xs;
}

.refresh-btn {
	padding: $spacing-sm;
	border-radius: $border-radius-base;
	background: $gray-100;
	transition: $transition-base;

	&:active {
		background: $gray-200;
	}
}

.refresh-icon {
	font-size: $font-size-lg;
}

/* 项目统计 */
.project-stats {
	display: flex;
	align-items: center;
	justify-content: space-around;
	padding: $spacing-lg 0;
	background: $gray-50;
	border-radius: $border-radius-lg;
}

.stat-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: $spacing-xs;
}

.stat-number {
	font-size: $font-size-xl;
	font-weight: 600;
	color: $primary-color;
}

.stat-label {
	font-size: $font-size-sm;
	color: $text-secondary;
}

.stat-divider {
	width: 1rpx;
	height: 60rpx;
	background: $border-color;
}

/* 项目详情面板 */
.project-panel {
	padding: $spacing-lg $spacing-xl $spacing-xl;
	position: relative;
}

.panel-drag-handle {
	width: 80rpx;
	height: 8rpx;
	background: $gray-300;
	border-radius: $border-radius-base;
	position: absolute;
	top: $spacing-md;
	left: 50%;
	transform: translateX(-50%);
}

.project-header {
	display: flex;
	justify-content: space-between;
	align-items: flex-start;
	margin-bottom: $spacing-lg;
	padding-top: $spacing-lg;
}

.project-info {
	flex: 1;
	margin-right: $spacing-md;
}

.project-name {
	font-size: $font-size-lg;
	font-weight: 600;
	color: $text-primary;
	margin-bottom: $spacing-xs;
	display: block;
}

.project-address {
	font-size: $font-size-sm;
	color: $text-secondary;
	line-height: 1.4;
}

.project-actions {
	display: flex;
	gap: $spacing-sm;
}

.action-btn {
	padding: $spacing-sm $spacing-md;
	border-radius: $border-radius-base;
	transition: $transition-base;

	&.primary {
		background: $primary-color;
		color: $text-white;

		&:active {
			background: $primary-dark;
		}
	}

	&.secondary {
		background: $gray-100;
		color: $text-secondary;

		&:active {
			background: $gray-200;
		}
	}
}

.btn-text {
	font-size: $font-size-sm;
	font-weight: 500;
}

/* 项目详情 */
.project-details {
	display: flex;
	flex-direction: column;
	gap: $spacing-md;
}

.detail-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: $spacing-md 0;
	border-bottom: 1rpx solid $border-light;

	&:last-child {
		border-bottom: none;
	}
}

.detail-label {
	font-size: $font-size-base;
	color: $text-secondary;
}

.detail-value {
	font-size: $font-size-base;
	color: $text-primary;
	font-weight: 500;
}

/* 状态标签 */
.status-badge {
	padding: $spacing-xs $spacing-sm;
	border-radius: $border-radius-sm;
	font-size: $font-size-xs;
	font-weight: 500;

	&.status-active {
		background: rgba(24, 144, 255, 0.1);
		color: $primary-color;
	}

	&.status-qualified {
		background: rgba(82, 196, 26, 0.1);
		color: $success-color;
	}

	&.status-unqualified {
		background: rgba(255, 77, 79, 0.1);
		color: $error-color;
	}
}

.status-text {
	font-size: inherit;
	color: inherit;
}
</style>